import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Image, Popconfirm, message, Modal, Dropdown, Progress } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, EyeOutlined, CopyOutlined, ExportOutlined } from '@ant-design/icons';
import { getActivityList, deleteActivity, updateActivityStatus, copyActivity, exportActivities } from '@/services/contentManagementApi';
import ActivityForm from './components/ActivityForm';
import ActivityDetail from './components/ActivityDetail';
import moment from 'moment';

const ActivityList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [activityFormVisible, setActivityFormVisible] = useState(false);
  const [activityDetailVisible, setActivityDetailVisible] = useState(false);
  const [currentActivity, setCurrentActivity] = useState<CONTENT.ActivityModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 状态标签颜色映射
  const statusColorMap = {
    draft: 'default',
    published: 'green',
    ended: 'orange',
    cancelled: 'red',
  };

  // 活动类型标签颜色映射
  const typeColorMap = {
    promotion: 'blue',
    competition: 'purple',
    festival: 'orange',
    learning: 'green',
  };

  // 表格列定义
  const columns: ProColumns<CONTENT.ActivityModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '活动封面',
      dataIndex: 'cover',
      width: 120,
      search: false,
      render: (_, record) => (
        <Image
          src={record.cover}
          alt={record.title}
          width={80}
          height={60}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '活动标题',
      dataIndex: 'title',
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '活动类型',
      dataIndex: 'type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        promotion: { text: '推广活动', status: 'Processing' },
        competition: { text: '竞赛活动', status: 'Warning' },
        festival: { text: '节日活动', status: 'Success' },
        learning: { text: '学习活动', status: 'Default' },
      },
      render: (_, record) => {
        const typeMap = {
          promotion: '推广活动',
          competition: '竞赛活动',
          festival: '节日活动',
          learning: '学习活动',
        };
        return (
          <Tag color={typeColorMap[record.type]}>
            {typeMap[record.type]}
          </Tag>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        draft: { text: '草稿', status: 'Default' },
        published: { text: '进行中', status: 'Success' },
        ended: { text: '已结束', status: 'Warning' },
        cancelled: { text: '已取消', status: 'Error' },
      },
      render: (_, record) => {
        const statusMap = {
          draft: '草稿',
          published: '进行中',
          ended: '已结束',
          cancelled: '已取消',
        };
        return (
          <Tag color={statusColorMap[record.status]}>
            {statusMap[record.status]}
          </Tag>
        );
      },
    },
    {
      title: '参与人数',
      dataIndex: 'participant_count',
      width: 100,
      search: false,
      render: (count) => count?.toLocaleString() || 0,
    },
    {
      title: '完成率',
      dataIndex: 'completion_rate',
      width: 120,
      search: false,
      render: (rate) => (
        <Progress
          percent={Math.round((rate || 0) * 100)}
          size="small"
          status={rate > 0.8 ? 'success' : rate > 0.5 ? 'normal' : 'exception'}
        />
      ),
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'copy',
                label: '复制',
                icon: <CopyOutlined />,
                onClick: () => handleCopy(record),
              },
              {
                key: 'status',
                label: getStatusAction(record.status),
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 获取状态操作文本
  const getStatusAction = (status: string) => {
    switch (status) {
      case 'draft':
        return '发布';
      case 'published':
        return '结束';
      case 'ended':
        return '重新发布';
      case 'cancelled':
        return '重新发布';
      default:
        return '更新状态';
    }
  };

  // 处理查看详情
  const handleViewDetail = (record: CONTENT.ActivityModel) => {
    setCurrentActivity(record);
    setActivityDetailVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: CONTENT.ActivityModel) => {
    setCurrentActivity(record);
    setEditMode('edit');
    setActivityFormVisible(true);
  };

  // 处理复制
  const handleCopy = async (record: CONTENT.ActivityModel) => {
    try {
      await copyActivity(record.id, `${record.title} - 副本`);
      message.success('活动复制成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('活动复制失败');
    }
  };

  // 处理状态变更
  const handleStatusChange = (record: CONTENT.ActivityModel) => {
    let newStatus: string;
    let actionText: string;
    
    switch (record.status) {
      case 'draft':
        newStatus = 'published';
        actionText = '发布';
        break;
      case 'published':
        newStatus = 'ended';
        actionText = '结束';
        break;
      case 'ended':
      case 'cancelled':
        newStatus = 'published';
        actionText = '重新发布';
        break;
      default:
        return;
    }
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}活动 "${record.title}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateActivityStatus(record.id, newStatus);
          message.success(`活动${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`活动${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: CONTENT.ActivityModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除活动 "${record.title}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteActivity(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentActivity(undefined);
    setEditMode('create');
    setActivityFormVisible(true);
  };

  // 处理导出
  const handleExport = async () => {
    try {
      const blob = await exportActivities({ format: 'excel' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `活动列表_${moment().format('YYYY-MM-DD')}.xlsx`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  return (
    <PageContainer>
      <ProTable<CONTENT.ActivityModel>
        headerTitle="活动列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建活动
          </Button>,
          <Button
            key="export"
            icon={<ExportOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getActivityList({
            page: params.current,
            limit: params.pageSize,
            title: params.title,
            type: params.type,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1600 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 活动表单弹窗 */}
      <ActivityForm
        visible={activityFormVisible}
        mode={editMode}
        initialValues={currentActivity}
        onCancel={() => setActivityFormVisible(false)}
        onSuccess={() => {
          setActivityFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 活动详情弹窗 */}
      <ActivityDetail
        visible={activityDetailVisible}
        activity={currentActivity}
        onCancel={() => setActivityDetailVisible(false)}
      />
    </PageContainer>
  );
};

export default ActivityList;
